<!--
 * @Description: 红包发放弹窗
 * @Author: liyujie
 * @Date: 2020/02/03
 * @Last Modified by: liyujie
 * @Last Modified time: 2020/02/03
-->
<template>
    <section class="wrapper">
        <el-dialog
            title="发放红包"
            :visible.sync="dialogVisible"
            width="840px"
            :close-on-click-modal="false"
            @close="handleClose"
        >
            <div>
                <!-- 筛选-->
                <div class="filter-view">
                    <div class="header-new-box">
                        <p class="header-new-box-title">用户注册手机号：</p>
                        <el-input
                            class="input-with-select"
                            placeholder="请输入用户注册手机号"
                            v-model="filterData.keyword"
                            clearable
                            size="small"
                            @keydown.enter.native="getTableData(1)"
                        />
                    </div>
                    <el-button
                        type="primary"
                        size="small"
                        class="search-btn"
                        @click="getTableData(1)"
                    >
                        搜索
                    </el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="fileDialog = true"
                    >
                        批量导入
                    </el-button>
                </div>
                <!-- table -->
                <el-table
                    :data="tableData"
                    max-height="438"
                    style="width: 100%;"
                    class="data-table"
                    v-if="tableData.length"
                >
                    <el-table-column
                        label="序号"
                        align="center"
                        width="60"
                        type="index"
                    />
                    <el-table-column
                        prop="true_name"
                        label="用户名"
                        align="center"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        prop="phone"
                        label="用户注册手机号"
                        align="center"
                    />
                    <el-table-column
                        prop="student_no"
                        label="用户编号"
                        align="center"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        label="发放数量"
                        align="center"
                        :width="isEdit ? '200' : ''"
                    >
                        <template slot-scope="scope">
                            <div
                                class="count-wrap"
                                v-show="!scope.row.editable"
                            >
                                {{ scope.row.issue_num }}
                                <el-button
                                    type="text"
                                    @click="setEditable(scope, true)"
                                >
                                    <i class="el-icon-edit"/>
                                </el-button>
                            </div>
                            <div
                                class="edit-count"
                                v-show="scope.row.editable"
                            >
                                <el-input-number
                                    v-model="scope.row.issue_num"
                                    style="width: 100px"
                                    size="mini"
                                    :min="1"
                                    :step="1"
                                    step-strictly
                                />
                                <div class="btn">
                                    <el-button
                                        type="text"
                                        @click="setCount(scope)"
                                    >
                                        确定
                                    </el-button>
                                    <el-button
                                        type="text"
                                        @click="setEditable(scope, false)"
                                    >
                                        取消
                                    </el-button>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                @click="handleDelete(scope.$index)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="medium"
                    :style="{width: '120px', marginRight: '24px'}"
                    @click="dialogVisible = false"
                >
                    取消
                </el-button>
                <el-button
                    type="primary"
                    size="medium"
                    :style="{width: '120px'}"
                    :disabled="tableData.length === 0"
                    @click="handleConfirm"
                    :loading="loading"
                >
                    确认发放
                </el-button>
            </span>
        </el-dialog>

        <!--批量导入弹窗-->
        <el-dialog
            title="批量导入"
            :visible.sync="fileDialog"
            width="540px"
            :close-on-click-modal="false"
            @close="file = null"
        >
            <div class="import-view">
                <el-upload
                    class="upload-demo"
                    ref="upload"
                    action="noAction"
                    accept=".csv"
                    :on-change="handleFileChange"
                    :show-file-list="false"
                    :auto-upload="false"

                >
                    <div
                        class="upload-view"
                        v-if="!file"
                    >
                        <i class="el-icon-upload2"/>
                        上传用户数据
                    </div>
                    <div
                        class="upload-view uploaded"
                        v-if="file"
                    >
                        <div>{{ file.name }} <span class="file-size">{{ formatFileSize(file.size) }}</span></div>
                        <div><i class="el-icon-upload2"/></div>
                    </div>
                </el-upload>
                <div class="bottom">
                    <div class="tips">
                        支持扩展名：.csv
                    </div>
                    <div>
                        <el-button
                            type="text"
                            @click="downloadTemplate"
                        >下载模板</el-button>
                    </div>
                </div>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="medium"
                    :style="{width: '120px', marginRight: '24px'}"
                    @click="fileDialog = false"
                >
                    取消
                </el-button>
                <el-button
                    type="primary"
                    size="medium"
                    :style="{width: '120px'}"
                    :loading="isUpload"
                    :disabled="!file"
                    @click="uploadFile"
                >
                    确认
                </el-button>
            </span>
        </el-dialog>

        <!--结果弹窗-->
        <el-dialog
            :visible.sync="resultDialog"
            width="396px"
            :close-on-click-modal="false"
            :show-close="false"
            custom-class="result-dialog"
        >
            <div class="result-view">
                <div class="result-icon">
                    <i :class="resultStatus ? 'el-icon-success': 'el-icon-error'"/>
                    <div>{{ resultStatus ? '红包发放成功' : '红包发放失败' }}</div>
                </div>
                <div class="result-reason">
                    <div
                        class="reason-label"
                        v-if="resultStatus === 1 && resultReasonList.length"
                    >以下用户发放失败：</div>
                    <div
                        class="reason-value"
                        style="font-size: 14px; text-align: center"
                        v-if="resultStatus === 0"
                    >
                        {{ resultReason }}
                    </div>
                    <div
                        class="reason-list"
                        v-if="resultStatus === 1 || resultReasonList.length"
                    >
                        <div
                            class="reason-value"
                            v-for="(item, index) in resultReasonList"
                            :key="index"
                        >
                            注册手机号{{ item.phone }}用户 失败原因：{{ item.issue_msg }}
                        </div>
                    </div>
                </div>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="medium"
                    :style="{width: '120px', marginRight: '24px'}"
                    @click="resultDialog = false"
                >
                    取消
                </el-button>
                <el-button
                    type="primary"
                    size="medium"
                    :style="{width: '120px'}"
                    @click="resultDialog = false"
                >
                    确认
                </el-button>
            </span>
        </el-dialog>
    </section>
</template>

<script>

export default {
    name: 'RedPacketGrant',
    computed: {},
    data() {
        return {
            // 红包编号
            packet_no: '',
            filterData: {
                keyword: ''
            },
            tableData: [],
            // 弹窗开关
            dialogVisible: false,
            loading: false,
            isEdit: false,
            // 上传文件弹窗
            fileDialog: false,
            file: null,
            isUpload: false,
            resultDialog: false,
            // 1成功 0失败
            resultStatus: 1,
            resultReason: '',
            resultReasonList: []
        };
    },
    mounted() {
    },
    methods: {
        /**
         * 显示弹窗
         * @param packet_no - 红包编号
         */
        show(packet_no) {

            this.packet_no = packet_no;
            this.dialogVisible = true;
        },
        /**
         * 关闭弹窗
         */
        close() {

            this.dialogVisible = false;
        },
        /**
         * 弹窗关闭 清空数据
         */
        handleClose() {
            this.filterData.keyword = '';
            this.tableData.length = 0;
        },
        /**
         * @description 获取列表
         * @param page
         */
        getTableData(page) {

            let params = {...this.filterData};

            this.$post('/student/shop_goods_red_packet%5Cget_issue_student', params, resp => {
                if (resp.code === 1) {
                    this.tableData = resp.data.list;
                    this.page = resp.data.page;
                    this.tableData.forEach(item => {
                        item.editable = false;
                    });
                    if(resp.data.list.length === 0) {
                        this.$message.warning('查询结果为空');
                    }
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },
        /**
         * 确认发放
         */
        handleConfirm() {
            this.loading = true;
            this.resultReasonList.length = 0;
            let params = {
                packet_no: this.packet_no,
                issue_json: JSON.stringify(this.tableData)
            };

            this.$post('/student/shop_goods_red_packet%5Cissue', params, resp => {
                if (resp.code === 1) {
                    this.dialogVisible = false;
                    this.fileDialog = false;
                    this.resultDialog = true;
                    this.resultReasonList = resp.data.list.filter(item => {
                        return item.issue_status === 0;
                    });
                    this.resultStatus = this.resultReasonList.length === resp.data.list.length ? 0 : 1;
                    this.$emit('update');
                    this.close();
                } else {
                    this.dialogVisible = false;
                    this.fileDialog = false;
                    this.resultReason = resp.msg;
                    this.resultStatus = 0;
                    this.resultDialog = true;
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
                this.loading = false;
            });
        },

        /**
         * 删除
         * @param index
         */
        handleDelete(index) {
            this.tableData.splice(index, 1);
        },

        /**
         * 点击编辑数量
         * @param row
         * @param $index
         * @param flag
         */
        setEditable({row, $index}, flag) {
            row.editable = this.isEdit = flag;
            if (flag) row.tempCount = row.issue_num;
            if (!flag) {
                row.issue_num = row.tempCount;
            }
            this.$set(this.tableData, $index, row);
        },

        /**
         * 设置数量
         * @param row
         * @param $index
         */
        setCount({row, $index}) {
            if (!row.issue_num) {
                this.$message.warning('数量不能为空');
                return;
            }
            row.editable = false;
            this.$set(this.tableData, $index, row);
        },

        /**
         * 上传文件发生变化
         * @param file
         * @param fileList
         */
        handleFileChange(file, fileList) {

            let isLt1M = file.size / 1024 / 1024 < 1;
            let fileType = file.name.split('.');

            if (fileType[fileType.length - 1] !== 'csv') {
                this.$notify({
                    title: '提示',
                    message: '仅支持 csv 格式文件',
                    type: 'warning',
                    duration: 2000
                });
                return;
            }

            if (!isLt1M) {
                this.$notify({
                    title: '提示',
                    message: '文件大小不能超过1M',
                    type: 'warning',
                    duration: 2000
                });
                return;
            }

            this.file = file;
        },
        /**
         * 格式化文件大小
         * @param fileSize
         * @param idx
         * @returns {string|*}
         */
        formatFileSize(fileSize, idx = 0) {
            const units = ["B", "KB", "MB", "GB"];

            if (fileSize < 1024 || idx === units.length - 1) {
                return fileSize.toFixed(1) + units[idx];
            }
            // eslint-disable-next-line no-param-reassign
            return this.formatFileSize(fileSize / 1024, ++idx);
        },
        /**
         * 文件上传
         */
        uploadFile() {
            this.isUpload = true;
            let file = new FormData();

            file.append('file', this.file.raw);
            this.$upload({
                url: '/student/shop_goods_red_packet%5Cget_issue_student_from_upload',
                data: file,
                success: resp => {
                    if (resp.code === 1) {
                        this.$notify({
                            title: '成功',
                            message: '导入成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.tableData = resp.data.list;
                        this.fileDialog = false;
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            type: 'warning',
                            duration: 2000
                        });
                    }
                    this.isUpload = false;
                },
            });
        },

        /**
         * 下载模板
         */
        downloadTemplate() {
            let base = this.$baseUrl;
            let ticket = localStorage.getItem('sessionTicket');
            let url = `${base}/student/shop_goods_red_packet%5Cget_issue_student_csv_demo?&__ticket=${ticket}`;

            window.open(url);
        }
    }
};
</script>

<style scoped lang="less">
.wrapper {
    /*筛选*/

    .filter-view {
        padding: 0 24px;
        margin: 6px 0 24px;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;

        .header-new-box {
            display: flex;
            align-items: center;
            color: #606266;
            white-space: nowrap;

            &-title {
                margin-right: 2px;
                white-space: nowrap;
            }
        }

        .search-btn {
            border-radius: 0 4px 4px 0;
        }
        .input-with-select {
            width: 300px;
            /deep/ .el-input__inner {
                border-radius: 4px 0 0 4px;
                border-right: 0;
            }
        }
    }

    .data-table {
        margin-bottom: 30px;

        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        ::-webkit-scrollbar-track {
            width: 6px;
            background: rgba(#101F1C, 0.1);
            -webkit-border-radius: 2em;
            -moz-border-radius: 2em;
            border-radius: 2em;
        }

        ::-webkit-scrollbar-thumb {
            background-color: rgba(#101F1C, 0.3);
            background-clip: padding-box;
            min-height: 28px;
            -webkit-border-radius: 2em;
            -moz-border-radius: 2em;
            border-radius: 2em;
        }

        ::-webkit-scrollbar-thumb:hover {
            background-color: rgba(#101F1C, 0.5);
        }

        ::-webkit-scrollbar-button {
            display: none;
        }

        .count-wrap {
            .el-button {
                font-size: 14px;
                line-height: 1;
                color: #ccc;

                &:hover {
                    color: #20a0ff;
                }
            }
        }

        .edit-count {
            display: flex;
            align-items: center;

            .btn {
                margin-left: 10px;
                display: flex;

                .el-button {
                    margin-left: 0;
                    margin-right: 10px;
                }
            }
        }
    }

    /*批量导入弹窗*/
    .import-view {
        display: flex;
        flex-direction: column;
        /deep/ .el-upload {
            width: 492px;
            .upload-view {
                width: 100%;
                height: 36px;
                line-height: 36px;
                text-align: center;
                border-radius: 4px;
                border: 1px dashed #C2C2C2;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #C2C2C2;
                box-sizing: border-box;
                padding: 0 12px;
                &.uploaded {
                    color: #333333;
                    display: flex;
                    justify-content: space-between;
                }
            }
            .file-size {
                margin-left: 12px;
            }
        }
        .bottom {
            display: flex;
            justify-content: space-between;
            .tips {
                font-size: 12px;
                color: #606266;
                margin: 12px 0;
            }
        }
    }
    /*结果弹窗*/
    /deep/ .result-dialog {
        min-height: 240px;
        .result-view {
            display: flex;
            flex-direction: column;
            align-items: center;
            .result-icon {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                margin-bottom: 14px;
                i {
                    font-size: 48px;
                    margin: 16px 0 12px;
                }
                .el-icon-success {
                    color: #2FBDB3;
                }
                .el-icon-error {
                    color: #F56C6C;
                }
            }
            .result-reason {
                width: 100%;
                display: flex;
                flex-direction: column;
                margin-bottom: 14px;
                .reason-label {
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #333333;
                    margin-bottom: 16px;
                }
                .reason-value {
                    font-size: 12px;
                    font-weight: 400;
                    color: #999999;
                    line-height: 14px;
                    margin-bottom: 10px;
                }
                .reason-list {
                    max-height: 300px;
                    overflow-y: auto;
                }
            }
        }
        .el-dialog__header {
            display: none!important;
        }
        .el-dialog__body {
            overflow: hidden!important;
        }
    }

    /deep/ .el-dialog {
        .el-dialog__header {
            padding-top: 10px;
            box-shadow: 0 1px 0 0 rgba(233, 233, 233, 1);
            display: flex;
            align-items: center;
            background: #FAFAFA;
            border-radius: 4px 4px 0 0;

            .el-dialog__title {
                font-weight: 500;
                color: #333;
                font-size: 14px;
            }

            .el-icon-close:before {
                color: rgb(194, 194, 194);
                font-size: 17px;
                font-weight: bold;
            }

            .el-dialog__headerbtn {
                top: 14px;
            }
        }

        .el-dialog__body {
            padding: 24px 24px 0;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }

        .el-textarea__inner {
            resize: none;
        }

        .el-dialog__footer {
            text-align: center;
            padding-bottom: 30px;
            margin-top: 6px;
        }
    }
}

</style>
